﻿using ModernChannel.Model.Interface;
using ModernChannel.Model.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ModernChannel.Provider
{
    public class SerialNumberRdcHistProvider : GenericProvider, ISerialNumberRdcHistProvider
    {
        public List<SerialNumberRdcHist> SearchSerialNumberRdcHist(string serial, string model, string sellOutStatus = null, int? serialNo = null)
        {
            var query = repository.GetQuery<SerialNumberRdcHist>();
            if (!string.IsNullOrWhiteSpace(sellOutStatus))
            {
                query = query.Where(x => x.SelloutStatus.Equals(sellOutStatus));
            }
            if (serialNo.HasValue)
            {
                query = query.Where(x => Int32.Parse(x.SerialNo.Substring(1, 3)) >= serialNo.Value);
            }
            return query.ToList();
        }


        public bool Update(SerialNumberRdcHist obj)
        {
            try
            {
                var invOrg = (obj.InvOrg ?? string.Empty).ToUpper();
                var model = (obj.Model ?? string.Empty).ToUpper();
                var suffix = (obj.Suffix ?? string.Empty).ToUpper();
                var ediNo = (obj.EdiNo ?? string.Empty).ToUpper();
                var serialNo = (obj.SerialNo ?? string.Empty).ToUpper();
                var updateRecord = Retrieve(obj.Model, obj.Suffix, obj.SerialNo);
                if (updateRecord == null) return false;

                updateRecord.BoxNo = obj.BoxNo;
                updateRecord.CreateDate = obj.CreateDate;
                updateRecord.IncentiveDate = obj.IncentiveDate;
                updateRecord.IncentiveFlag = obj.IncentiveFlag;
                updateRecord.LineNo = obj.LineNo;
                updateRecord.ModelSuffix = obj.ModelSuffix;
                updateRecord.SelloutDate = obj.SelloutDate;
                updateRecord.SelloutStatus = obj.SelloutStatus;
                updateRecord.ShipNo = obj.ShipNo;
                updateRecord.SmsYn = obj.SmsYn;
                updateRecord.WtIfDate = obj.WtIfDate;
                updateRecord.WtIfFlag = obj.WtIfFlag;
                repository.UnitOfWork.SaveChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }

        public SerialNumberRdcHist Retrieve(string models, string suffixes, string serialNumber)
        {
            var model = (models ?? string.Empty).ToUpper();
            var suffix = (suffixes ?? string.Empty).ToUpper();
            var serialNo = (serialNumber ?? string.Empty).ToUpper();
            var updateRecord = repository.FindOne<SerialNumberRdcHist>(k => k.Model.ToUpper() == model && k.Suffix.ToUpper() == suffix && k.SerialNo.ToUpper() == serialNo);
            return updateRecord;
        }
    }
}
